<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="shoowaddcate">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <!-- 是否有效 -->
      <tree-table
        class="treeTable"
        :selection-type="false"
        :expand-type="false"
        :data="catelist"
        :columns="columns"
        show-index
        index-text="#"
        border
      >
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color: lightgreen"
          ></i>
          <i class="el-icon-error" v-else style="color: red"></i>
        </template>
        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" type="success" v-if="scope.row.cat_level === 0"
            >一级</el-tag
          >
          <el-tag
            size="mini"
            type="warning"
            v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag size="mini" v-else>三级</el-tag>
        </template>
        <!-- 操作区域 -->
        <template slot="opt" slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="showeditcate(scope.row.cat_id)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="removecatebyid(scope.row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="querrInfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="querrInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addcatedialogVisible"
      width="50%"
      @close="addcateclosed"
    >
      <!-- 添加分类的表单 -->
      <el-form
        :model="addCateForm"
        :rules="addCateFormrules"
        ref="addCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称:" prop="cate_name">
          <el-input v-model="addCateForm.cate_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类:">
          <el-cascader
            expand-trigger="hover"
            v-model="selectkeys"
            :options="parentCatelist"
            :props="cascaderProps"
            @change="parentcatchaange"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addcatedialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addcate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑栏 -->
    <el-dialog
      title="编辑分类"
      :visible.sync="editcate"
      width="50%"
      @close="editclosed"
    >
      <el-form
        :model="editcateForm"
        :rules="editcateFormrules"
        ref="editcateFormRef"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editcateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editcate = false">取 消</el-button>
        <el-button type="primary" @click="editcate1">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //查询条件
      querrInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      //商品分类的数据列表
      catelist: [],
      //数据列表数量
      total: 0,
      //为table指定列
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name',
        },
        {
          label: '是否有效',
          //将当前列定义为模板列
          type: 'template',
          //当前这一列使用模板名称
          template: 'isok',
        },
        {
          label: '排序',
          type: 'template',
          template: 'order',
        },
        {
          label: '操作',
          type: 'template',
          template: 'opt',
        },
      ],
      //默认添加对话窗口不打开
      addcatedialogVisible: false,
      //添加分类的表单数据对象
      addCateForm: {
        //将要添加的分类名称
        cate_name: '',
        //父级分类id
        cate_pid: 0,
        //默认添加一级分类
        cate_level: 0,
      },
      //添加分类表单验证规则
      addCateFormrules: {
        cate_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
        ],
      },
      //创建的父级分类列表
      parentCatelist: [],
      //指定级联选择器的配置对象
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      //选中的父级分类保存
      selectkeys: [],
      editcate: false,
      //查询到的分类名称
      editcateForm: {},
      editcateFormrules: {
        cat_name: [
          { required: true, message: '请输入分类名称', tigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '请输入长度在3到10个字符之间的分类名',
            tigger: 'blur',
          },
        ],
      },
    }
  },
  created() {
    this.getCatelist()
  },
  methods: {
    async getCatelist() {
      const { data: res } = await this.$http.get('categories', {
        params: this.querrInfo,
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类错误')
      }
      //把数据列表赋值给catelist
      this.catelist = res.data.result
      //赋值获取到的数据数量
      this.total = res.data.total
    },
    //监听pagesize改变
    handleSizeChange(newSize) {
      this.querrInfo.pagesize = newSize
      this.getCatelist()
    },
    //监听pagenume改变
    handleCurrentChange(newPage) {
      this.querrInfo.pagenum = newPage
      this.getCatelist()
    },
    //点击添加显示对话窗口
    shoowaddcate() {
      this.addcatedialogVisible = true
      this.getParentCateList()
    },
    //获取父级分类数据列表
    async getParentCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 },
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类数据失败')
      }
      this.parentCatelist = res.data
    },
    //选中项发生变化
    parentcatchaange() {
      console.log(this.selectkeys)
      //如果selectkeys>0证明选中
      if (this.selectkeys.length > 0) {
        this.addCateForm.cate_pid = this.selectkeys[this.selectkeys.length - 1]
        this.addCateForm.cate_level = this.selectkeys.length
        return
      } else {
        this.addCateForm.cate_pid = 0
        this.addCateForm.cate_level = 0
      }
    },
    // 增加分类
    addcate() {
      this.$refs.addCateFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post('categories', {
          cat_pid: this.addCateForm.cate_pid,
          cat_name: this.addCateForm.cate_name,
          cat_level: this.addCateForm.cate_level,
        })
        if (res.meta.status !== 201) {
          return this.$message.error('添加分类失败！')
        }

        this.$message.success('添加分类成功！')
        this.getCatelist()
        this.addcatedialogVisible = false
      })
    },
    addcateclosed() {
      this.$refs.addCateFormRef.resetFields()
      this.selectkeys = []
      this.addCateForm.cate_level = 0
      this.addCateForm.cate_pid = 0
    },
    async removecatebyid(id) {
      //弹框提示是否删除数据
      const confirmResult = await this.$confirm(
        '此操作将永久删除该分类, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      //若点击确认删除，返回confirm字符串
      //若点击取消删除，返回cancel字符串
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('categories/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除分类失败')
      }
      this.$message.success('成功删除分类')
      this.getCatelist()
    },
    async showeditcate(id) {
      this.editcate = true
      const { data: res } = await this.$http.get('categories/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类名称失败')
      }
      this.editcateForm = res.data
    },
    editclosed() {
      this.$refs.editcateFormRef.resetFields()
    },
    editcate1() {
      this.$refs.editcateFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'categories/' + this.editcateForm.cat_id,
          { cat_name: this.editcateForm.cat_name }
        )
        if (res.meta.status !== 200) return this.$message.error('更新分类失败')

        this.$message.success('更新分类成功')
        this.getCatelist()
        this.editcate = false
      })
    },
  },
}
</script>
    
<style lang="less" scoped>
.treeTable {
  margin-top: 15px;
}
.el-cascader {
  width: 100%;
}
</style>